from rest_framework import viewsets, status, filters
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend

from weiwenhai_Oj.deprecated.request_params import request_params
from weiwenhai_Oj.utils.global_functions import returnResponse, PageSizePagination
from ..filter.problem_filter import ProblemFilter
from ..models.problem_model import ProblemModel
from ..serializers.problem_serializer import (
    ProblemListSerializer,
    ProblemDetailSerializer,
    ProblemCreateSerializer,
    ProblemUpdateSerializer, ProblemSerializer
)
from ..services.problem_service import ProblemService
from rest_framework import serializers




class ProblemViewSet(viewsets.ModelViewSet):
    """
    题目管理视图集
    """
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    queryset = ProblemModel.objects.filter(is_delete=False)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, )
    filterset_class = ProblemFilter
    ordering_fields = ['create_time', 'update_time', 'difficulty']
    ordering = ['-create_time']
    paginator = PageSizePagination()

    def get_serializer_class(self):
        if self.action == 'list':
            return ProblemListSerializer
        elif self.action == 'create':
            return ProblemCreateSerializer
        elif self.action == 'update':
            return ProblemUpdateSerializer
        return ProblemDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return returnResponse({
            'code': 200,
            'msg': '获取成功',
            'data': serializer.data
        })

    def list(self, request, *args, **kwargs):
        """获取题目列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return returnResponse({
                'code': 200,
                'msg': '获取成功',
                'count': self.get_paginated_response(serializer.data).data.get('count'),
                'data': self.get_paginated_response(serializer.data).data.get('results')
            })

        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code': 200,
            'message': 'success',
            'data': serializer.data
        })

    @action(methods=['get'], detail=False)
    def count(self, request, *args, **kwargs):
        """获取题目数量"""
        queryset = self.filter_queryset(self.get_queryset())
        return Response({
            'code': 200,
            'message': 'success',
            'data': queryset.count()
        })

    @action(methods=['post'], detail=False)
    @request_params(need_user=True)
    def delete(self, problem_id, user):
        """删除题目"""
        if user.is_staff:
            res = ProblemService().delete_problem(problem_id)
        else:
            return returnResponse({'code': 403, 'msg': '您没有权限删除题目'})
        if res:
            return returnResponse({'code': 200, 'msg': '删除成功'})
        return returnResponse({'code': 200, 'msg': '删除失败'})

    @action(methods=['get'], detail=False, url_path='types')
    def get_types(self, request):
        """获取题目类型"""
        types = ProblemService().get_problem_types()
        return returnResponse({'code': 200, 'msg': 'success', 'data': types})


    @action(methods=['get'], detail=False, url_path='tags')
    def get_tags(self, request):
        """获取题目标签"""
        tags = ProblemService().get_problem_tags()
        return returnResponse({'code': 200, 'msg': 'success', 'data': tags})

    @action(methods=['post'], detail=False, url_path='save')
    @request_params(need_user=True, serializer_class=ProblemSerializer, unpack=False)
    def create_or_update(self, forms, user):
        if not user.is_staff:
            return returnResponse({'code': 403, 'msg': '无权操作'})
        forms = forms.data
        res = ProblemService().save_problem(problem_id=forms['id'], **forms)
        if res:
            return returnResponse({'code': 200, 'msg': '操作成功'})
        return returnResponse({'code': 500, 'msg': '操作失败'})
